package it.managerService;


import it.Dao.BooksDao;
import it.domain.Books;
import it.domain.PageBean;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * 条件查询&分页
 *
 * @author wsx
 * @create 2020-04-06-16:40
 */
@WebServlet("/pageServlet")
public class pageServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String number = req.getParameter("number");
        //System.out.println("number"+number);
        //获取当前页码
        BooksDao booksDao = new BooksDao();
        PageBean pageBean = new PageBean();
        String currentPagess = req.getParameter("currentPage");

        if (currentPagess == null || "".equals(currentPagess)) {
            currentPagess = "1";
        }
        String currentPages = currentPagess.trim();
        Integer currentPage = Integer.valueOf(currentPages);
        //防止点上一页时越界
        if (currentPage <= 1) {
            currentPage = 1;
        }
        //获取条件查询的参数
        Map<String, String[]> condition = req.getParameterMap();

        //总记录数
        Long totalCount = null;
        try {
            totalCount = booksDao.totalCount(condition);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        int total;
        if (totalCount == null) {
            total = 0;
        } else {
            total = totalCount.intValue();
        }
        pageBean.setTotalCount(total);
        //每页的数据
        Integer counts = 8;
        //总页数
        double pageCount = Math.ceil(1.0 * pageBean.getTotalCount() / counts);
        pageBean.setTotalPage((int) pageCount);
        //防止下一页越界
        if (currentPage >= pageBean.getTotalPage()) {
            currentPage = pageBean.getTotalPage();
        }
        pageBean.setCurrPage(currentPage);
        //查询数据角标开始位置
        Integer index = (pageBean.getCurrPage() - 1) * counts;
        try {
            List<Books> list = booksDao.getPageData(index, counts, condition);
            //Collections.reverse(list);//反转集合 让添加的书籍在第一个显示
            pageBean.setBooksList(list);
        } catch (SQLException e) {
            e.printStackTrace();
        }
//        Set<String> strings = condition.keySet();
//        for (String key:strings){
//            String value=condition.get(key)[0];
//            System.out.println(key+":"+value+"666");
//        }
        req.setAttribute("condition", condition);
        req.setAttribute("pageBean", pageBean);
        //转发
        req.getRequestDispatcher("books_page.jsp").forward(req, resp);

    }
}
